<template>
  <!-- 面包屑 -->
  <Breadcrumb />
  <el-card class="box-card">

    <el-row class="row-bg">
      <el-col :span="8">
        <el-input
          v-model="formInfo.query"
          placeholder="查询用户名"
          class="input-with-select"
          clearable
          @change="getDataList"
        >
          <template #append>
            <el-button :icon="Search" @click="getDataList" />
          </template>
        </el-input>

      </el-col>
      <el-button class="btn" type="primary" @click="addUser">添加用户</el-button>
  </el-row>
  <!-- 表格 -->
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column
      :prop="item.prop"
      :label="item.label"
      v-for="(item,index) in listName"
      :key="index"
      :width="item.width"
    >
      <!-- 自定义（插槽） -->
      <!-- 状态 -->
      <template #default="{row}" v-if="item.prop === 'mg_state'">
        <el-switch v-model="row.mg_state" @change="setStateType(row)" />
      </template>
      <!-- 编辑功能 -->
      <template #default="{row}" v-if="item.prop === 'action'">
        <el-button type="primary" :icon="Edit" circle @click="addUser(row)" />
        <el-button type="danger" :icon="Delete" circle @click="deleteUser(row)" />
        <el-tooltip
          class="box-item"
          effect="dark"
          content="分配角色"
          placement="top"
          :enterable='enterable'
        >
          <el-button type="success" :icon="Setting" circle @click="assign(row)" />
        </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页器 -->
  <el-pagination
    v-model:currentPage="formInfo.pagenum"
    v-model:page-size="formInfo.pagesize"
    :page-sizes="[1, 3, 5, 15]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
  </el-card>
  <!-- 对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="Tips"
    width="50%"
  >
    <!-- 内容区域 -->
    <el-form
    ref="formRef"
    label-width="70px"
    :model="ruleForm "
    style="max-width: 460px"
    :rules="rules"
    v-if="Tips!=='分配角色'"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="Tips==='添加用户'">
        <el-input v-model="ruleForm.password" type="password" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="ruleForm.email" />
      </el-form-item>
      <el-form-item label="电话" prop="mobile">
        <el-input v-model="ruleForm.mobile" />
      </el-form-item>
    </el-form>
    <!-- 分配用户对话框 -->
    <template v-else>
      <p>当前的用户: {{assignInfo.username}}</p>
      <p>当前的角色: {{assignInfo.role_name}}</p>
      <p>分配新角色：
         <el-select v-model="selectedRoleId" class="m-2" placeholder="Select">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
      </p>
    </template>
    

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addData"
          >确认</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import Breadcrumb from '@/components/Breadcrumb.vue'
import { Search } from '@element-plus/icons-vue'
import { getUsers, setState, addUserData, editUser, delUser, allocation, getrolesList } from '@/api/user'
import { Edit, Delete, Setting } from '@element-plus/icons-vue'


// 总条数
const total = ref(0)
// 表格数据模型
const listName = ref([
  { label: 'Id', prop: 'id' },
  { label: '姓名', prop: 'username' },
  { label: '邮箱', prop: 'email' },
  { label: '电话', prop: 'mobile' },
  { label: '角色', prop: 'role_name' },
  { label: '状态', prop: 'mg_state' },
  { label: '操作', prop: 'action', width: '180px' }
])
// 初始值
const formInfo = ref({
  query: '',
  pagenum: 1,
  pagesize: 3
})

// 表格数据
const tableData = ref([])
const getDataList = async () => {
  const res = await getUsers(formInfo.value)
  tableData.value = res.data.data.users
  total.value = res.data.data.total
  formInfo.pagenum
  console.log(res.data.data)
}
getDataList()
// 点击页码事件
const handleSizeChange = (pageSize) => {
  console.log(pageSize)
  formInfo.value.pagesize = pageSize
  getDataList()
}
const handleCurrentChange = (pagenum) => {
  formInfo.value.pagenum = pagenum
  // console.log(pageSize)
  getDataList()
}

// 修改状态
const setStateType = async (row) => {
  console.log(row)
  const res = await setState(row.id, row.mg_state)
  getDataList()
  ElMessage({
    message: '更新成功',
    type: 'success',
  })
  console.log(res)
}

// 添加用户对话框
const Tips = ref('')
const dialogVisible = ref(false)
const addUser = (row) => {
  dialogVisible.value = true

  if (row.id) {
    Tips.value = '编辑用户'
    ruleForm.value = JSON.parse(JSON.stringify(row))
  } else {
    Tips.value = '添加用户'
    ruleForm.value = {}
  }
}
// 添加时form表单的初始状态
const ruleForm = ref({
  username: '',
  password: '',
  email: '',
  mobile: ''
})
// 验证信息
const formRef = ref(null)
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  mobile: [
    { required: true, message: '请输入电话号码', trigger: 'blur' }
  ]
})
// 验证规则以及确认添加数据
const addData = async () => {
  if (Tips.value!== '分配角色') {
    // 添加与编辑用户
    formRef.value.validate(async (valid) => {
      if (valid) {
        // 判断是否为编辑/添加 发送对应请求
        if (Tips.value === '添加用户') {
          await addUserData(ruleForm.value)
          ElMessage({
            message: '添加成功',
            type: 'success',
          })
        } else if (Tips.value === '编辑用户') {
          await editUser(ruleForm.value)
          ElMessage({
            message: '编辑成功',
            type: 'success',
          })
        }
        getDataList()
        dialogVisible.value = false
        // 清空对话框
        ruleForm.value = {}
      } else {
        console.log('error submit!')
        return false
      }
    })
  } else {
    // 分配角色
    const res = await allocation(assignInfo.value, { rid: selectedRoleId.value })
    console.log(selectedRoleId.value)
    dialogVisible.value = false
    getDataList()
  }
}
// 删除功能
const deleteUser = async (row) => {
  ElMessageBox.confirm(
    '此操作将永久删除该用户, 是否继续?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
  const res = await delUser(row)
  getDataList()
}
// 分配角色
const enterable = ref(false)
const assignInfo = ref('')
const selectedRoleId = ref()
const options = ref([])
const assign = async (row) => {
  dialogVisible.value = true
  Tips.value = '分配角色'
  assignInfo.value = row
  console.log(assignInfo.value.id)
  // 发送请求获取角色列表
  const res = await getrolesList()
  options.value = res.data.data

}

</script>

<style scoped lang="less">
.el-card{
  .el-table{
    margin-top: 15px;
  }
  margin-top: 15px;
  .btn{
    margin-left: 15px;
  }
  .el-pagination{
    margin-top: 5px;
  }
  .el-form{
    .p{
      margin-bottom: 5px;
    }
  }
}
</style>
